#include "ReagentInfoDialog.h"
#include "ui_ReagentInfoDialog.h"
#include <QSqlRecord>
#include <QTime>
#include <QDebug>

ReagentInfoDialog::ReagentInfoDialog(int id, MySqlTableModel *model, QWidget *parent) :
    QDialog(parent), model(model),
    m_id(id),
    ui(new Ui::ReagentInfoDialog)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);//隐藏标题设置为顶层显示  
    InitUi();
}

ReagentInfoDialog::~ReagentInfoDialog()
{
    delete ui;
}

void ReagentInfoDialog::InitUi()
{
    QSqlRecord record = model->record(m_id);
    QVector<QString> name;
    name<<"reagName"<<"openDate"<<"margin";

    bool ok = model->recordContains(&record, name);  // 查询记录字段是否存在
    if(!ok)
    {
        return;
    }

    QString reagName = record.value(name.at(0)).toString();
    QString openDate = record.value(name.at(1)).toString();
    QString margin = record.value(name.at(2)).toString();

    ui->en_reagent->setText(reagName);
    ui->nu_dateEdit->setDateTime(QDateTime::fromString(openDate ,"yyyy-MM-dd"));
    ui->nu_remainder->setText(margin);
}


void ReagentInfoDialog::on_Btn_OK_clicked()
{  
    QString reagName = ui->en_reagent->text();
    QString openDate = ui->nu_dateEdit->date().toString(Qt::ISODate);
    QString margin = ui->nu_remainder->text();

    QSqlRecord record = model->record(m_id);

    QVector<QString>name;
    QVector<QVariant>value;
    name<<"regName"<<"openData"<<"margin";
    value<<reagName<<openDate<<margin;

    bool ok = model->recordSetValue(&record, name, value);  //设置记录字段的值
    if(!ok)
    {
        return;
    }

    model->database().transaction();  //开始事务处理
    if(model->submitAll()){
        model->database().commit();   //提交
    } else {
        model->database().rollback();  //回滚
    }

    close();
}

void ReagentInfoDialog::on_Btn_close_clicked()
{
    close();
}
